package com.asman.vr.network

import com.asman.vr.constant.ErrorCode
import com.asman.vr.dto.BaseRes
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
// todo sp
//import sp
//import spExit

abstract class MyRetrofitCallback<R>(private val interceptCodeError: Boolean = false) :
    Callback<BaseRes<R>> {

    enum class ErrorType {
        CodeError, NetWorkError,
    }

    override fun onFailure(call: Call<BaseRes<R>>, t: Throwable) {
        onError(ErrorType.NetWorkError, call, "", "网络异常，请检查网络")
    }

    override fun onResponse(call: Call<BaseRes<R>>, response: Response<BaseRes<R>>) {
        if (response.isSuccessful) {
            if (response.body()?.code == ErrorCode._10000) {
                if (response.body()?.result == null) {
                    onError(
                        ErrorType.CodeError, call, response.body()?.code ?: "",
                        response.body()?.error ?: "result返回了null"
                    )
                } else {
                    onSuccess(call, response.body()?.result!!, response.body()?.datetime ?: "0")
                }
            } else {
                //是否拦截code error的情况下的默认操作--比如为true时，不进行跳转登录页面
                if (!interceptCodeError) {
                    if (ErrorCode.tokenLoseEfficacy(response.body()?.code)) { //token 失效了
                        // todo sp
                        //  sp.spExit()
                        // todo 跳转登陆
                        /*RouterUtils.get(RouterUrl.LoginChoiceActivity)
                            .navigation()*/
                    }
                }
                onError(
                    ErrorType.CodeError, call, response.body()?.code ?: "",
                    response.body()?.error ?: "出了一点小差，请稍后重试"
                )
            }
        } else {
            onError(
                ErrorType.NetWorkError, call, response.body()?.code ?: "",
                "网络异常，请检查网络"
            )
        }
    }

    abstract fun onSuccess(call: Call<BaseRes<R>>, result: R, datetime: String) //状态码成功

    //除了success的所有error
    open fun onError(errorType: ErrorType, call: Call<BaseRes<R>>, code: String, msg: String) {
        if (errorType == ErrorType.CodeError) {
            onCodeError(call, code, msg)
        } else if (errorType == ErrorType.NetWorkError) {
            onNetWorkError(call, msg)
        }
    }

    //状态码错误
    open fun onCodeError(call: Call<BaseRes<R>>, code: String, msg: String) {}

    //网络错误
    open fun onNetWorkError(call: Call<BaseRes<R>>, msg: String) {}

}